package db

import (
	"fmt"
	mydb "togethorGo/db/mysql"
)

// UserInfo : 用户信息结构体
type UserInfo struct {
	Username string
	Password string
}

// HandleUserInfo :
func HandleUserInfo(username, password string) (UserInfo, error) {
	stmt, err := mydb.DBConn().Prepare("select (`user_name`, `password`) form tbl_user where user_name = ? and password=?")
	if err != nil {
		return UserInfo{}, err
	}
	userInfo := UserInfo{}
	res := stmt.QueryRow(username, password).Scan(&userInfo.Username, &userInfo.Password)
	fmt.Println(res)

	return userInfo, nil
}

// HandleUserRegister : 注册用户写入数据库
func HandleUserRegister(username, encpassword string) error {
	stmt, err := mydb.DBConn().Prepare("insert into tbl_user(`user_name`,`password`) values(?,?)")
	if err != nil {
		return err
	}
	ret, err := stmt.Exec(username, encpassword)
	if err != nil {
		return err
	}
	if err != nil {
		return err
	}
	rowsAffected, err := ret.RowsAffected()
	//rowsAffected大于0才算插入成功
	if err == nil && rowsAffected > 0 {
		return nil
	}
	return err

}

// HandleUserUnregister ：注销用户
func HandleUserUnregister(username, encpassword string) error {
	stmt, err := mydb.DBConn().Prepare("delete from  tbl_user where user_name=? and password=?")
	if err != nil {
		return err
	}
	ret, err := stmt.Exec(username, encpassword)
	if err != nil {
		return err
	}
	rowsAffected, err := ret.RowsAffected()
	//rowsAffected大于0才算插入成功
	if err == nil && rowsAffected > 0 {
		return nil
	}
	return err
}
